package com.example.xinhuazidian.base

import com.example.xinhuazidian.base.API.Api
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import java.util.concurrent.TimeUnit

/**
 * Description : RetrofitService
 */
class RetrofitService private constructor() {
    /**
     * 获取api对象
     *
     * @return api对象
     */
    val apiService: Api

    companion object {
        @Volatile
        private var apiRetrofit: RetrofitService? = null

        /**
         * 单例调用
         *
         * @return RetrofitService
         */
        val instance: RetrofitService?
            get() {
                if (apiRetrofit == null) {
                    synchronized(Any::class.java) {
                        if (apiRetrofit == null) {
                            apiRetrofit = RetrofitService()
                        }
                    }
                }
                return apiRetrofit
            }
    }

    /**
     * 初始化retrofit
     */
    init {

        //配置okHttp并设置时间、日志信息和cookies
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        val okHttpClient = OkHttpClient.Builder()
            .addInterceptor(httpLoggingInterceptor) //设置超时时间
            .connectTimeout(30, TimeUnit.SECONDS) //设置Cookie持久化
            //                .cookieJar(new CookiesManager(YUtils.getApplication()))
            .build()

        //关联okHttp并加上rxJava和Gson的配置和baseUrl
        val retrofit = Retrofit.Builder()
            .client(okHttpClient)
            .addConverterFactory(BaseConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl(API.BASE_URL_UPDATA)
            .build()
        apiService = retrofit.create(Api::class.java)
    }
}